import React, { useEffect } from 'react';
import s from './style.module.css';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import Table from '@knownsec/react-component/dist/Table';
import Tabs, { TabPane } from '@kuiper-components/tabs';
import cn from 'classnames';
import { portCol, osCol, webCol, webTaskCol, httpCol, jobCol } from '../columns';
import Label from '../../../../../components/Label';
import fetchFer from 'API/fetch';
import Icon from '@knownsec/react-component/dist/Icon'
import Tooltip from '@knownsec/react-component/dist/Tooltip'
import InfoDisplay from './InfoDisplay';
import InfoTable from './InfoTable';
import Monitor from './Monitor';
import { GetQueryString } from '../../../../../helpers/getUrlParams';
import { FREQUENCY_UNIT_MAP as UNIT,
	SSL_CATEGORY_KEY_LABEL_MAP,
	SECURITY_EVENT_TYPE_MAP,
	CONTENT_KEYWORD_TYPES,
	CONTENT_PRIVACY_DISCLOSURE_TYPES } from '../../../../../../common/constants';
import ms from 'ms';
import moment from 'moment'

const taskTypeMap = { vul: 'Web漏洞监测', ssl: 'SSL安全监测', security_event: '安全事件监测', content: '内容违规监测' };
const timeList = ['天', '时', '分', '秒']
const profile = ['全量漏洞', '低危漏洞', '中危漏洞', '高危漏洞'];
function Detail({
	match: {
		params: { assetType },
	},
	jid,
	location,
	tid,
	atid,
	data,
	taskType,
	task_types,
	history,
	isHistory
}) {
	const aviliableNode = JSON.parse(sessionStorage.aviliableNode);
	const tag = GetQueryString(location.search, 'tag') || 'vul';
	const type = GetQueryString(location.search, 'type');
	const [hostInfo, setHostInfo] = React.useState({});
	const [info, setInfo] = React.useState({});
	const [vulnsMap, setVulnsMap] = React.useState(null)
	const [vulnsList, setVulnsList] = React.useState([])

	const timeChange = value => {
		let unit;
		let num;
		if (value) {
			const freq = ms(value);
			unit = value ? freq.replace(/\d*/, '') : 'd';
			num = parseInt(freq.replace(/[a-zA-Z]/, ''), 10);
			if (value % ms('30d') === 0) {
				unit = 'month';
				num = value / ms('30d');
			} else if (value % ms('1w') === 0) {
				unit = 'w';
				num = value / ms('1w');
			}
		}
		return `${num}${UNIT[unit]}1次`;
	};
	const getVulnsList = async () => {
		const res = await fetchFer(`/api/v2/vulndb/kb_vulns`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		const mapData = {}
		const data = res.data.map(item => {
			mapData[item.source_id] = item.name.zh_cn
			return { label: item.name.zh_cn, value: item.source_id}
		})
		setVulnsMap(mapData)
		setVulnsList(data)
	}
	const taskContent = (data, map, text) => {
		let res = '- -'
		if (data?.length > 0) {
			if (text && data.length === Object.keys(map).length) {
				res = text
			} else if (data.length > 2) {
				res = <>
					{data.slice(0, 2).map(item => { return map[item] }).join('、')}等{data.length}类
					<Tooltip overlay={<div style={{maxWidth: '300px', maxHeight: '200px', overflow: 'auto'}}>{data.map(item => { return map[item] }).join('、')}</div>} placement={'top'}>
						<Icon type={'detail'} className={cn(s.mainColor, s.cp, s.ml5, s.vam)} />
					</Tooltip>
				</>
			} else {
				res = data.slice(0, 2).map(item => { return map[item] }).join('、')
			}
		}
		return res
	}
	const respInfo = React.useMemo(() => {
		let fast = null
		let slowest = null
		data?.result?.addition?.detail?.map(item => {
			if (!fast || fast.totalTime > item.totalTime) {
				fast = item
			}
			if (!slowest || slowest.totalTime < item.totalTime) {
				slowest = item
			}
		})
		const res = {
			avg: data?.result?.addition?.respAvg,
			fast,
			slowest
		}
		return res
	}, [data])
	const infoTableData = React.useMemo(() => {
		const allNode = aviliableNode?.v4_area?.concat(aviliableNode?.v6_area).reduce((t, i) => {
			const item = JSON.parse(JSON.stringify(i));
			delete item.enable;
			t[Object.keys(item)[0]] = item[Object.keys(item)[0]];
			return t
		}, {})
		const settingsIPv4 = data?.task_settings?.collect?.area?.map(i => { return { node: i, networkDisplayName: 'IPv4' } }) || []
		const settingsIPv6 = data?.task_settings?.collect?.area_ipv6?.map(i => { return { node: i, networkDisplayName: 'IPv6' } }) || []
		const res = Object.values(data?.result?.addition?.detail?.concat(settingsIPv4)?.concat(settingsIPv6)?.reduce((total, item) => {
			if (!total[`${item.node}_${item.networkDisplayName}`]) {
				if (item.area) {
					item.endTime = data?.end_time
					item.taskType = data?.task_type
				} else {
					item.area = allNode[item.node]
					item.securityStatus = 'error'
				}
				total[`${item.node}_${item.networkDisplayName}`] = item
			}
			return total
		}, {}) || {})
		return res
	}, [data])
	useEffect(() => {
		// getVulnsList()
	}, []);
	return (
		<Tabs className={s.tabs}>
			<TabPane key="overview" tab="概况">
				<div className={cn(s.df, s.aic, s.mt10, s.labelColor, s.mb20)}>
					<Label className={s.m0}>最近一次监测详情</Label>
					<Icon className={cn(s.ml10, s.mr5)} type='time' />
					<span>{moment(data?.end_time).format('YYYY-MM-DD HH:mm:ss')}</span>
				</div>
				<InfoDisplay key={'last'}
					chartData={{ 异常: data?.result?.addition?.nodeAbnormalCount, 正常: (data?.result?.addition?.nodeTotalCount - data?.result?.addition?.nodeAbnormalCount) < 0 ? 0 : (data?.result?.addition?.nodeTotalCount - data?.result?.addition?.nodeAbnormalCount)}}
					abnormalNodes={data?.result?.addition?.detail?.reduce((t, item) => {
						if (item.securityStatus === 'warning') {
							t.push(item.area)
						}
						return t
					}, []) || []}
					respInfo={respInfo}/>
				<InfoTable taskType={data?.task_type} data={infoTableData} />
				<Label className={s.mt20}>可用性统计</Label>
				{data?.target && <Monitor key={`${data?.task_type}${data?.target}`}
					jobId={jid}
					taskType={data?.task_type}
					target={data?.target}/>}
			</TabPane>
			<TabPane key="history" tab="历史快照">
				<InfoTable className={s.mt20} type='history' jobId={jid}
					taskType={data?.task_type}
					target={data?.target} />
			</TabPane>
		</Tabs>
	);
}
Detail.propTypes = {
	tid: PropTypes.string.isRequired,
	atid: PropTypes.string.isRequired,
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(Detail);
